package cn.dsp.admin.service.impl;

import cn.dsp.admin.entity.Permission;
import cn.dsp.admin.mapper.PermissionMapper;
import cn.dsp.admin.service.IPermissionService;
import cn.dsp.admin.service.ex.DeleteException;
import cn.dsp.admin.service.ex.InsertException;
import cn.dsp.admin.service.ex.UserNotFoundException;
import cn.dsp.admin.service.ex.UsernameConflictException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PermissionServiceImpl implements IPermissionService {
   @Autowired
   private PermissionMapper mapper;

    @Override
    public void insertPerm(Permission permission) {
        Permission result = getByName(permission.getName());
        if (result!=null){
            throw new UsernameConflictException("改项目已存在");
        }
        Integer rows = mapper.savePerm(permission);
        if (rows!=1){
            throw new InsertException("添加权限失败");
        }
    }

    @Override
    public Permission getByName(String name) {
        return  mapper.findPermByName(name);

    }

    @Override
    public Permission getByPId(Integer pid) {
        Permission result = mapper.findPermByPid(pid);
        if (result==null){
            throw new UserNotFoundException("无此数据");
        }
        return result;
    }

    @Override
    public void changePermByPid(Permission permission) {
        Permission result = getByPId(permission.getPid());
        mapper.updatePermByPid(permission);
    }

    @Override
    public void deletePermByPid(Integer pid) {
         Integer rows = mapper.removePermByPid(pid);
         if (rows!=1){
             throw new DeleteException("删除数据失败！");
         }
    }

    @Override
    public List<Permission> getPermAll() {
        return mapper.findPermAll();
    }
}
